//
//  ConfirmGiftOrderViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/7/30.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit
//兑换商品确认订单页面
class ConfirmGiftOrderViewController: UIViewController{
    @IBOutlet weak var uv_back: UIView!
    @IBOutlet weak var usv_add: UIStackView!
    @IBOutlet weak var uv_add: UIView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var phone: UILabel!
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lb_total: UILabel!
    @IBOutlet weak var lb_submit: UILabel!
    @IBOutlet weak var uv_top: UIView!
    var giftid:String!
    var count:String!
    var addressid:String!
    var dataSource=[mGiftConfrimGiftList]()
    init(giftid:String!,count:String!){//第一个参数礼品ID 第二个参数兑换数量
        super.init(nibName: nil, bundle: nil)
        self.giftid=giftid
        self.count=count
        GiftConfirmOrder()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        uv_top.layer.cornerRadius=10
        tableView.dataSource=self
        tableView.delegate=self
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "GiftCell", bundle: nil), forCellReuseIdentifier: "re")
        tableView.backgroundColor="#E9E9E9".color()
        uv_back.addOnClickListener(target: self, action: #selector(back))
        uv_add.addOnClickListener(target: self, action: #selector(addaddr))
        usv_add.addOnClickListener(target: self, action: #selector(addaddr))
        lb_submit.addOnClickListener(target: self, action: #selector(GiftSubmitOrder))
        NotificationCenter.default.addObserver(self, selector: #selector(update), name: NSNotification.Name("choose"), object: nil)
        // Do any additional setup after loading the view.
    }
    @objc func showPop(){
        
    }
    @objc func update(noti: Notification){
        let addr=noti.object as!mShippingAddress
        addressid=String(addr.Id)
        name.text=addr.ShipTo!
        phone.text=addr.Phone!
        address.text="\(addr.RegionFullName!)\(addr.Address!)"
    }
    @objc func addaddr(){
        self.navigationController?.pushViewController(AddressViewController(choose: true), animated: true)
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    func GiftConfirmOrder(){
        var d = ["userkey":userkey,
                 "id":giftid,
                 "count":count,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.post(url: ConfirmOrder, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            let result=mGiftConfrimResult.init(json: res)
            let address=result.ShipAddress
            ss.addressid="\(String(describing: address?.Id))"
            ss.name.text=address?.ShipTo
            ss.phone.text=address?.Phone
            ss.address.text="\(address?.RegionFullName! ?? "")\(address?.Address! ?? "")"
            ss.dataSource=result.GiftList
            ss.lb_total.text="兑换\(ss.dataSource.count)件礼品，\(result.TotalAmount)西瓜币"
            ss.tableView.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func GiftSubmitOrder(){
        if addressid==nil{
            HUD.showText("请添加收货地址！")
        }
        var d = ["userkey":userkey,
                 "regionId":addressid,
                 "id":giftid,
                 "count":count,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.post(url: SubmitOrder, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["success"].boolValue{
                HUD.showText("恭喜您，礼品兑换成功！")
                ss.navigationController?.jumpViewControllerAndCloseSelf(vc: OrderViewController(index: 0))
            }
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension ConfirmGiftOrderViewController:UITableViewDataSource,UITableViewDelegate{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "re") as! GiftCell
        cell.layer.cornerRadius=10
        let item=dataSource[indexPath.row]
        cell.selectionStyle = .none
        cell.icon.setImage(path: URL.init(string: item.DefaultImage!)!)
        cell.name.text=item.GiftName
        cell.price.text="\(item.SaleIntegral)"
        cell.count.text="x\(item.Quantity)"
        return cell
    }


}
